<!--suppress HtmlDeprecatedAttribute -->
<template>
  <div class="pagePermissionWrapper">
    <permission-dialog v-model="dialogVisible" :type="dialogType" :id="dialogId" @update="freshTable"/>
    <xum-title title="查询条件" :title-span="6">
      <el-button @click="freshAllTable" size="small" icon="el-icon-refresh" type="primary"
                 :disabled="paginationDisabled" :loading="paginationDisabled">查询</el-button>
    </xum-title>
    <el-form ref="form" :model="form" label-width="120px" size="small" :disabled="paginationDisabled">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="权限ID" prop="permissionId">
            <el-input type="text" v-model="form.permissionId" placeholder="权限ID"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="权限编号" prop="permissionCode">
            <el-input type="text" v-model="form.permissionCode" placeholder="权限编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="权限名称" prop="permissionName">
            <el-input type="text" v-model="form.permissionName" placeholder="权限名称"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="top">
      <xum-title :title-span="6" title="权限列表">
        <el-button size="small" :icon="buttonsFlag ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
                   @click="buttonBox"/>
        <el-button v-if="buttonsFlag" @click="handleClearSort" size="small"
                   :disabled="paginationDisabled">清除排序</el-button>
        <el-button @click="handleRemoveMore" type="danger" size="small" icon="el-icon-delete-solid"
                   :disabled="paginationDisabled || !isFirst ? '' : null">删除选择</el-button>
        <el-button @click="handleDialogAdd" type="primary" icon="el-icon-plus"
                   size="small">添加权限</el-button>
      </xum-title>
    </div>
    <el-tabs v-model="activeTable">
      <el-tab-pane label="自定义权限" :name="tabFirst">
        <div class="table">
          <el-table ref="table" size="small" :data="tableData" style="width: 100%" height="449" max-height="600"
                    v-loading='paginationDisabled' @selection-change="handleSelectionChange"
                    :default-sort="tableSort" @sort-change="handleSortChange" :border="true">
            <el-table-column type="selection" align="center" width="50" fixed="left"/>
            <el-table-column prop="permissionId" align="center" label="权限ID" columnKey="permissionId"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="permissionCode" align="center" label="权限编号" columnKey="permissionCode"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="permissionName" align="center" label="权限名称" columnKey="permissionName"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="permissionDesc" align="center" label="权限描述" columnKey="permissionDesc"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="createUserId" align="center" label="创建人员编号" columnKey="createUserId"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="createUserName" align="center" label="创建人员名称" columnKey="createUserName"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="createTime" align="center" label="创建时间" columnKey="createTime"
                             resizable sortable="custom" width="210"/>
            <el-table-column label="操作" align="center" fixed="right" resizable width="200">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleDialogEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleRemove(scope.row)" style="color: red;">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change='handleCurrentChange'
                         :page-size.sync='size' :total.sync="total" :current-page.sync="page" background
                         :disabled="paginationDisabled" layout="sizes, total, jumper, prev, pager, next"/>
        </div>
      </el-tab-pane>
      <el-tab-pane label="系统权限" :name="tabSecond">
        <div class="table">
          <el-table ref="table2" size="small" :data="tableData2" style="width: 100%" height="449" max-height="600"
                    v-loading='paginationDisabled2' :default-sort="tableSort2" @sort-change="handleSortChange2"
                    :border="true">
            <el-table-column prop="permissionId" align="center" label="权限ID" columnKey="permissionId"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="permissionCode" align="center" label="权限编号" columnKey="permissionCode"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="permissionName" align="center" label="权限名称" columnKey="permissionName"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="permissionDesc" align="center" label="权限描述" columnKey="permissionDesc"
                             resizable sortable="custom" width="150"/>
            <el-table-column prop="createUserId" align="center" label="创建人员编号" columnKey="createUserId"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="createUserName" align="center" label="创建人员名称" columnKey="createUserName"
                             resizable sortable="custom" width="210"/>
            <el-table-column prop="createTime" align="center" label="创建时间" columnKey="createTime"
                             resizable sortable="custom" width="210"/>
          </el-table>
          <el-pagination class="pagination" @size-change="handleSizeChange2" @current-change='handleCurrentChange2'
                         :page-size.sync='size2' :total.sync="total2" :current-page.sync="page2" background
                         :disabled="paginationDisabled2" layout="sizes, total, jumper, prev, pager, next"/>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ResultCode } from '@/constants/constants'
import PageDTO from '@/api/entity/PageDTO'
import { queryPermissionPageWrapper, removePermission } from '@/api/ApiPermission'
import PermissionQueryDTO from '@/api/entity/PermissionQueryDTO'
import BusinessConstants from '@/constants/BusinessConstants'
import PermissionDialog from '@pages/resource/part/pagePermission/PermissionDialog'
import XumTitle from '@/components/XumTitle'

export default {
  name: 'PagePermission',
  components: { XumTitle, PermissionDialog },
  data () {
    return {
      tabFirst: 'first',
      tabSecond: 'second',
      activeTable: 'first',
      buttonsFlag: true,
      tableSort: {},
      tableSort2: {},
      dialogVisible: false,
      dialogType: '',
      dialogId: 0,
      tableData: [],
      tableData2: [],
      selection: [],
      sortData: this.tableSort,
      sortData2: this.tableSort2,
      filterData: {},
      filterData2: {},
      loading: false,
      loading2: false,
      total: 0,
      size: 10,
      page: 1,
      total2: 0,
      size2: 10,
      page2: 1,
      filterColumns: {
        category: [],
        group: [],
        sellPoint: [],
        state: []
      },
      filterColumns2: {
        category: [],
        group: [],
        sellPoint: [],
        state: []
      },
      form: {
        permissionId: '',
        permissionCode: '',
        permissionName: ''
      }
    }
  },
  computed: {
    isFirst () {
      return this.activeTable && this.activeTable === this.tabFirst
    },
    paginationDisabled () {
      return this.loading
    },
    paginationDisabled2 () {
      return this.loading2
    },
    selectIds () {
      const ids = []
      this.selection.forEach(item => {
        ids.push(item.permissionId)
      })
      return ids
    }
  },
  methods: {
    buttonBox () {
      this.buttonsFlag = !this.buttonsFlag
    },
    /**
     * 打开添加权限对话框
     */
    handleDialogAdd () {
      this.dialogType = 'add'
      this.dialogId = 0
      this.dialogVisible = true
    },
    /**
     * 打开编辑权限权限对话框
     * @param val 数据
     */
    handleDialogEdit (val) {
      this.dialogType = 'edit'
      this.dialogId = val.permissionId
      this.dialogVisible = true
    },
    /**
     * 移除一个数据
     * @param val 数据
     */
    handleRemove (val) {
      if (val && val.permissionId) {
        this.$confirm('此操作将永久删除该权限信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const id = val.permissionId
          removePermission([id], data => {
            if (data.code === ResultCode.OK) {
              this.$message.success('移除权限成功')
              this.activeTable = this.tabFirst
              this.dialogVisible = false
              this.freshTable()
            }
          })
        }).catch(() => {
        })
      }
    },
    /**
     * 清除排序
     */
    handleClearSort () {
      this.$refs['table'].clearSort()
      this.sortData = {}
      this.$refs['table2'].clearSort()
      this.sortData2 = {}
      this.freshAllTable()
    },
    /**
     * 清除筛选
     */
    handleClearFilter () {
      this.$refs['table'].clearFilter()
      this.filterData = {}
      this.page = 1
      this.$refs['table2'].clearFilter()
      this.filterData2 = {}
      this.page2 = 1
      this.freshAllTable()
    },
    /**
     * 移除选择的多个数据
     */
    handleRemoveMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望移除的权限')
        return
      }
      this.$confirm('此操作将永久删除这' + this.selectIds.length + '条权限信息，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePermission(this.selectIds, data => {
          if (data.code === ResultCode.OK) {
            this.$message.success('移除权限成功')
            this.activeTable = this.tabFirst
            this.dialogVisible = false
            this.freshTable()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 选择发生改变回调，同步数据
     * @param val 选择的数据，数组
     */
    handleSelectionChange (val) {
      this.selection = val
    },
    /**
     * 格式化时间格式
     * @param {Array} time 时间数组
     */
    formatTime (time) {
      if (!time) {
        return ''
      }
      for (let i = 1; i < time.length; i++) {
        time[i] = time[i] < 10 ? '0' + time[i] : '' + time[i]
      }
      return time[0] + '-' + time[1] + '-' + time[2] + ' ' + time[3] + ':' + time[4] + ':' + time[5]
    },
    dialogSuccess () {
      this.dialogVisible = false
      this.freshTable()
    },
    freshAllTable () {
      this.freshTable()
      this.freshTable2()
    },
    /**
     * 更新表格数据，size和page改变时都会调用
     */
    freshTable () {
      this.loading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size)
      pageDTO.setCurrent(this.page)
      const condition = PermissionQueryDTO.instance()
        .addPermissionId(this.form.permissionId)
        .addPermissionCode(this.form.permissionCode)
        .addPermissionName(this.form.permissionName)
      // 排序
      if (this.sortData && this.sortData.prop && this.sortData.order) {
        if (this.sortData.order === 'descending') {
          condition.addOrderDesc(this.sortData.prop)
        } else if (this.sortData.order === 'ascending') {
          condition.addOrderAsc(this.sortData.prop)
        }
      }
      // 筛选
      Object.keys(this.filterData).forEach(key => {
        if (this.filterData[key].length > 0) {
          condition.addFilter(key, this.filterData[key])
        }
      })
      condition.setCreateMode([BusinessConstants.PERMISSION_CREATE_MODE_HAND])
      pageDTO.setCondition(condition)
      queryPermissionPageWrapper(pageDTO, data => {
        if (data.code === ResultCode.OK) {
          this.tableData = data.object['records']
          this.tableData.forEach(item => {
            item.createTime = this.formatTime(item['createTime'])
          })
          this.total = data.object['total']
        }
      }, () => {
        this.loading = false
      })
    },
    /**
     * 更新表格数据，size和page改变时都会调用2
     */
    freshTable2 () {
      this.loading2 = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size2)
      pageDTO.setCurrent(this.page2)
      const condition = PermissionQueryDTO.instance()
      // 排序
      if (this.sortData2 && this.sortData2.prop && this.sortData2.order) {
        if (this.sortData2.order === 'descending') {
          condition.addOrderDesc(this.sortData2.prop)
        } else if (this.sortData2.order === 'ascending') {
          condition.addOrderAsc(this.sortData2.prop)
        }
      }
      // 筛选
      Object.keys(this.filterData2).forEach(key => {
        if (this.filterData2[key].length > 0) {
          condition.addFilter(key, this.filterData2[key])
        }
      })
      condition.setCreateMode([BusinessConstants.PERMISSION_CREATE_MODE_SELF])
      pageDTO.setCondition(condition)
      queryPermissionPageWrapper(pageDTO, data => {
        if (data.code === ResultCode.OK) {
          this.tableData2 = data.object['records']
          this.tableData2.forEach(item => {
            item.createTime = this.formatTime(item['createTime'])
          })
          this.total2 = data.object['total']
        }
      }, () => {
        this.loading2 = false
      })
    },
    /**
     * size改变更新数据
     */
    handleSizeChange () {
      this.page = 1
      this.freshTable()
    },
    /**
     * size改变更新数据2
     */
    handleSizeChange2 () {
      this.page2 = 1
      this.freshTable2()
    },
    /**
     * 排序改变监听，刷新页面
     * { column, prop, order }
     */
    handleSortChange (val) {
      this.sortData = val
      this.freshTable()
    },
    /**
     * 筛选改变监听
     */
    handleFilterChange (val) {
      Object.assign(this.filterData, val)
      this.page = 1
      this.freshTable()
    },
    /**
     * 排序改变监听，刷新页面2
     * { column, prop, order }
     */
    handleSortChange2 (val) {
      this.sortData2 = val
      this.freshTable2()
    },
    /**
     * page改变更新数据
     */
    handleCurrentChange () {
      this.freshTable()
    },
    /**
     * page改变更新数据2
     */
    handleCurrentChange2 () {
      this.freshTable2()
    }
  },
  mounted () {
    this.freshAllTable()
  }
}
</script>

<style scoped lang="scss">
.pagePermissionWrapper{

    .table {
      margin: 16px 0;
      text-align: center;

      .pagination {
        margin: 20px auto;
      }
    }

}
</style>
